<?php
namespace app\custom_user\model;

class UserSession
{
    static protected $key="user_session";
    static public function init($token="")
    {
        if($token){
            if(session_status()===PHP_SESSION_ACTIVE){
                session_commit();
            }
            session_id($token);
            session_start();
        }
        else{
            if(session_status()===PHP_SESSION_NONE){
                session_start();
            }
        }
    }
    static public function token()
    {
        if(session_status()===PHP_SESSION_NONE){
            session_start();
        }
        return session_id();
    }
    static public function get()
    {
        if(session_status()===PHP_SESSION_NONE){
            session_start();
        }
        if(!isset($_SESSION[self::$key])){
            return false;
        }
        return $_SESSION[self::$key];
    }
    static public function set($data)
    {
        if(session_status()===PHP_SESSION_NONE){
            session_start();
        }
        $_SESSION[self::$key]=$data;
    }
    static public function clear()
    {
        if(session_status()===PHP_SESSION_NONE){
            session_start();
        }
        $_SESSION[self::$key]=null;
    }
    /**
     * 将指定用户踢下线
     * @param $token 需要踢下线的用户
     */
    static public function ban($token)
    {
        $current="";
        if(session_status()===PHP_SESSION_ACTIVE){
            $current=session_id();
            session_commit();
        }
        session_id($token);
        session_start();
        $_SESSION[self::$key]=null;
        session_commit();
        if($current){
            session_id($current);
            session_start();
        }
    }
}
